/**
 * @namespace
 */
aws.modules.keygrabber = {
	listSubscribers: function() {
		return {
			"init": this.init
		}
	},
	/**
	 * Sets handlers to detect when user presses keys. Handlers checks if system should be notified of particular event, and, if so, sends those notifications. 
	 * Also deals with crossbrowser inconsistentcy.
	 */
	init: function() {
		/**
		 * Checks if event didn't come from form elements and no key modifiers were pressed
		 * @param {Object} e
		 */
		function targetAndModifiersOk(e) {
			return !($(e.target).is('input') || $(e.target).is('textarea') || e.ctrlKey || e.altKey);
		}
		function getKeyType(e) {
			if (typeof e.which == 'undefined' || e.which !== 0) {
				return 'normal';
			} else {
				return 'special';
			}
		}
		// Webkit detects 8 && 27 only on keyup/keydown. Opera detects it on keypress and keyup/keydown, but lets prevent default action only on keypress.
		$(document).bind('keydown.aws', function(e, charCode, keyType) {
			var code = charCode || e.keyCode, keyType = keyType || getKeyType(e);
			if (targetAndModifiersOk(e) && (code == 8 || code == 27) && !$.browser.opera) {
				notify('keypress', [code, e, keyType]);
			}
		});
		$(document).bind('keypress.aws', function(e, charCode, keyType) {
			var code = charCode || e.charCode || e.keyCode, keyType = keyType || getKeyType(e);
			if (targetAndModifiersOk(e) && code != 8 || targetAndModifiersOk(e) && code == 8 && $.browser.opera) {
				notify('keypress', [code, e, keyType]);
			}
		});
	}
};
